#####################################################
# Replication Archive: Crumbling in the Face of Cost?
# Mader, Neubert, Münchow, Hofmann, Schoen & Gavras
# 01/2024
#####################################################
# Figure 3: Treatment effects by country
#####################################################

# define which packages are needed 
p_needed <-
  c("broom", "hrbrthemes", "viridis", "ggh4x", "tidyverse",
    "sjPlot", "dotwhisker", "gridExtra", "grid", "extrafont",
    "ggrepel", "hrbrthemes", "ggExtra")

# check which packages are already installed
packages <- rownames(installed.packages())

# check which of the packages you need are not installed 
p_to_install <- p_needed[!(p_needed %in% packages)]

# install missing packages 
if (length(p_to_install) > 0) {
  install.packages(p_to_install)
}
# load required packages 
sapply(p_needed, require, character.only = TRUE)

###################################################

# load data
load("EUP_Costs_ReplicationData.RData")

# Experiment 1: Military Intervention
countryModel_ex1 <- dat %>%
  group_by(QCOUNTRY) %>%
  group_map(~ broom::tidy(lm(costExperiment1_CrisisManagement ~ costExperiment1_Treat1 +
                               costExperiment1_Treat2,
                             data = .x)))

# add country names
names(countryModel_ex1) <- unique(dat$QCOUNTRY)

# transform to dataframe and clean data
countryModel_ex1Data <- bind_rows(countryModel_ex1, .id = "QCOUNTRY") %>%
  filter(term == "costExperiment1_Treat1SoldiersRisk" |
           term == "costExperiment1_Treat2CountryCost"  |
           term == "costExperiment1_Treat2SharedCost") %>%
  mutate(term = as.factor(term)) %>%
  dplyr::rename(model = QCOUNTRY) %>%
  mutate(model = as.factor(model)) %>%
  dplyr::rename(model1 = term,
                term = model) %>%
  dplyr::rename(model = model1) %>%
  mutate(model = fct_recode(model,
                            `Casualties` = "costExperiment1_Treat1SoldiersRisk",
                            `National Budget` = "costExperiment1_Treat2CountryCost",
                            `Pooled Budget` = "costExperiment1_Treat2SharedCost"),
         ex = "Military Intervention")


# Experiment 2: Defence procurement
countryModel_ex2 <- dat %>%
  group_by(QCOUNTRY) %>%
  group_map(~ broom::tidy(lm(costExperiment2_Aircraft ~  costExperiment2_Treat1 +
                               costExperiment2_Treat2,
                             data = .x)))

# add country names
names(countryModel_ex2) <- unique(dat$QCOUNTRY)

# transform and clean data
countryModel_ex2Data <- bind_rows(countryModel_ex2, .id = "QCOUNTRY") %>%
  filter(term == "costExperiment2_Treat1JobCuts" |
           term == "costExperiment2_Treat2CountryCost" |
           term == "costExperiment2_Treat2SharedCost") %>%
  mutate(term = as.factor(term)) %>%
  dplyr::rename(model = QCOUNTRY) %>%
  mutate(model = as.factor(model)) %>%
  dplyr::rename(model1 = term,
                term = model) %>%
  dplyr::rename(model = model1) %>%
  mutate(model = fct_recode(model, `Job Cuts` = "costExperiment2_Treat1JobCuts",
                            `National Budget` = "costExperiment2_Treat2CountryCost",
                            `Pooled Budget` = "costExperiment2_Treat2SharedCost"),
         ex = "Defence Procurement")


# bind data from both experiments
all_experiments_country <- rbind(countryModel_ex1Data,
                                 countryModel_ex2Data
)

# define characteristics for strips
font_strips <- strip_nested(
  # Horizontal strips
  size = "constant",
  text_x = elem_list_text(face = c("bold", "italic"),
                          size = c(24,20)),
  by_layer_x = TRUE,
  bleed = TRUE,
  clip = "off"
)

# relevel model variable
all_experiments_country$model <- forcats::fct_relevel(all_experiments_country$model,
                                                      "Casualties",
                                                      "Job Cuts",
                                                      "National Budget",
                                                      "Pooled Budget")


# combined plot of both experiments
plot_countryModel_ex <- ggplot(all_experiments_country,
                               aes(estimate, fct_rev(term)
                               )) +
  geom_vline(xintercept = 0, lty = 2, color = "grey", size = 0.75) +
  geom_point(size = 3, position = position_dodge(.2)) +
  geom_linerange(aes(xmin = estimate -1.96*std.error,
                     xmax = estimate + 1.96*std.error),
                 size = 1.5,
                 position = position_dodge(.2),
                 alpha = 0.6) +
  theme_ipsum_rc(grid="XY",
                 axis_title_size = 14,
                 axis_text_size = 18,
                 strip_text_size = 36) +
  labs(y = "", x = "") +
  facet_nested(~ factor(ex, levels = c("Military Intervention", "Defence Procurement"))  +
                 factor(model), strip = font_strips) +
  theme(legend.position = "none",
        legend.title= element_blank()) +
  lims(x = c(-0.25, 0.15)) +
  #coord_flip() +
  theme(strip.text = element_text(hjust = .5))

# manually build figure
gt <- ggplot_gtable(ggplot_build(plot_countryModel_ex))

# define spacing between facets
gt$widths[7] = 0.325*gt$widths[7]
gt$widths[11] = 0.25*gt$widths[11]
gt$widths[15] = 1*gt$widths[15]
gt$widths[19] = 0.25*gt$widths[19]
gt$widths[23] = 0.25*gt$widths[23]

# draw plot
grid.draw(gt)

# save figure
ggsave("plots/mainTreatmentEffect_Countries.png", 
       gt, device = "jpeg", width = 4600 , height = 3000, units = "px")

